<!--  -->
<template>
  <div class="News">
    <!-- <p>新闻{{ name }}</p> -->
    <p>数量：{{ count }}</p>
    <el-button type="primary" @click="builderData">生成数据</el-button>
    <el-button type="primary" @click="saveData">保存数据</el-button>
    <el-button type="primary" @click="readData">读取数据</el-button>
    <el-button type="primary" @click="singleData('202210004')"
      >单个数据</el-button
    >
    <el-button type="primary" @click="pagesData">分页数据</el-button>
    <el-button type="primary" @click="countData">统计数据</el-button>
    <p v-if="initList.length > 0" style="color: #ff0000;">生成成功</p>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { myMixin } from "@/mixins/mixins";
export default {
  mixins: [myMixin],
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      initList: [],
      list: [],
      db: "",
      count: 0
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    initDB() {
      if (!window.indexedDB) {
        console.log("你的浏览器在生成订单中可能存在异常");
        return false;
      }
      let request = indexedDB.open("myDB");
      // err
      request.onerror = event => {
        console.log("数据库打开/创建报错", event);
      };

      //如果指定的版本号，大于数据库的实际版本号，就会发生数据库升级事件upgradeneeded。
      //升级后自动触发success
      request.onupgradeneeded = event => {
        let store;
        let db = event.target.result;
        this.db = db;
        //建表 名为person,主键为id
        if (!db.objectStoreNames.contains("simInfo")) {
          store = db.createObjectStore("simInfo", {
            keyPath: "iccid"
          });
        }
        //新建索引名称、索引所在的属性、配置对象（说明该属性是否允许有重复的值）
        store.createIndex("name", "name", {
          unique: false
        });
        store.createIndex("age", "age", {
          unique: false
        });

        console.log("数据库升级");
      };

      // success
      request.onsuccess = event => {
        this.db = event.target.result;
        console.log("数据库打开/创建成功", event);
      };
    },
    // 生成数据
    builderData() {
      for (let i = 0; i < 50000; i++) {
        this.initList.push({
          iccid: "2022" + i,
          name: "yangyi" + i,
          age: Math.floor(Math.random() * 10),
          time: new Date().getTime(),
          data: Math.floor(Math.random() * 10) + i,
          status: 1
        });
      }
    },
    // 保存数据
    saveData() {
      console.log("保存数据：", this.initList);
      console.time();
      this.initList.forEach(item => {
        this.clickAdd(item);
      });
      console.timeEnd();
    },

    // 写入操作
    clickAdd(data) {
      // 建立读写事务,向对象仓库写入数据记录
      let request = this.db
        .transaction(["simInfo"], "readwrite")
        .objectStore("simInfo")
        .add(data);
      request.onsuccess = event => {
        console.log(1);
        this.count++;
      };

      request.onerror = err => {
        console.log(2);
      };
    },

    countData() {
      let store = this.db
        .transaction(["simInfo"], "readonly")
        .objectStore("simInfo");
      let count = store.count();
      count.onsuccess = function(e) {
        console.log(e.target.result);
      };
    },
    //读取单个数据
    singleData(key) {
      let store = this.db
        .transaction(["simInfo"], "readonly")
        .objectStore("simInfo");

      var getOne = store.get(key);
      getOne.onerror = event => {
        console.log("查询失败");
      };
      getOne.onsuccess = event => {
        //通过key查询到的数据
        console.log("单条数据：", getOne.result);
        console.log("查询成功");
      };
    },
    //读取所有数据
    readData() {
      let store = this.db
        .transaction(["simInfo"], "readonly")
        .objectStore("simInfo");
      let list = [];
      // 遍历数据库
      store.openCursor().onsuccess = event => {
        let cursor = event.target.result;
        if (cursor) {
          list.push(cursor.value);
          cursor.continue();
        } else {
          this.list = list;
          console.log("数据：", this.list);
        }
      };
    },
    //分页查询
    pagesData() {
      let page = 1,
        pageSize = 10,
        data = [];
      let store = this.db
        .transaction(["simInfo"], "readonly")
        .objectStore("simInfo");
      let requeset = store.openCursor();
      let count = store.count();
      let index = null;
      requeset.onsuccess = function(event) {
        let res = event.target.result;
        if (res) {
          if (index === pageSize - 1) {
            data.push(res.value);
            console.log("读取数据成功：", data);
            console.log("总条目", count.result);
            return;
          }
          if (index === null && page !== 1) {
            console.log("读取跳过：", (page - 1) * pageSize);
            index = 0;
            res.advance((page - 1) * pageSize);
          } else {
            index++;
            data.push(res.value);
            res.continue();
          }
        } else {
          console.log("读取数据成功：", data);
          console.log("总条目", count.result);
        }
      };
      requeset.onerror = function() {
        console.log("读取数据失败");
      };
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.initDB();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
</style>
